package org.jeecgframework.web.controller;

import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.*;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.service.CbsGgReconditionServiceI;
import org.jeecgframework.web.service.CbsMerchineMoveServiceI;
import org.jeecgframework.web.service.CbsServiceServiceI;
import org.jeecgframework.web.service.WxCommonService;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.SendMailUtil;
import org.jeecgframework.web.util.StaticValue;
import org.jeecgframework.web.util.sendWxMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @Title: Controller
 * @Description: cbs_gg_recondition
 * @author onlineGenerator
 * @date 2017-01-06 16:01:21
 * @version V1.0   
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/cbsMerchineMoveController")
public class CbsMerchineMoveController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(CbsMerchineMoveController.class);

	@Autowired
	private CbsMerchineMoveServiceI cbsMerchineMoveService;
	@Autowired
	private SystemService systemService;

    @Autowired
    private WxCommonService wxCommonService;
	@Autowired
	private CbsServiceServiceI cbsServiceServiceI;

	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * cbs_gg_recondition列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "cbsGgRecondition")
	public ModelAndView cbsGgRecondition(HttpServletRequest request) {
		return new ModelAndView("com/zybk/cbsggrecondition/cbsGgReconditionList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(CbsMerchineMoveEntity merchineMoveEntity, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(CbsGgReconditionEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, merchineMoveEntity, request.getParameterMap());
		try{
		//自定义追加查询条件
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.cbsMerchineMoveService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}


	/*
	* 原微信申请设备移机功能
	* */
	/**
	 * 添加cbs_gg_recondition
	 * 
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(CbsMerchineMoveEntity merchineMoveEntity, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "添加成功";
		try{
            merchineMoveEntity.setServiceId(wxCommonService.generateServiceId(WxCommonService.ServiceEnum.GGFX));
			cbsMerchineMoveService.save(merchineMoveEntity);
            wxCommonService.sendServiceMail(WxCommonService.ServiceEnum.SBYJ,merchineMoveEntity.getId());
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "添加失败";
			throw new BusinessException(e.getMessage());
		}
        j.setObj(merchineMoveEntity.getServiceId());
		j.setMsg(message);
		return j;
	}


	//当前日期转化为MMdd字符转
	public String getDateStr(Date date) {
		SimpleDateFormat df = new SimpleDateFormat("MMdd");
		String dateStr = df.format(date);
		return dateStr;
	}
	/*
	* 现微信申请设备移机功能
	* 开发人：马宏刚
	* 时间：2018-04
	* */
	@RequestMapping(params = "doAddNew")
	@ResponseBody
	public AjaxJson doAddNew( HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String openId = oConvertUtils.getString(request.getSession().getAttribute("openId"));
		String name = oConvertUtils.getString(request.getSession().getAttribute("name"));
		System.out.println("openId--"+openId);
		TSUser user=systemService.singleResult("from TSUser where openId='"+openId+"'");
		String createBy="";
		String createName="";
		if(user!=null && StringUtil.isNotEmpty(user.getUserName())){
			createBy=user.getUserName();
		}else{
			createBy=openId;
		}
		if(user!=null && StringUtil.isNotEmpty(user.getRealName())){
			createName=user.getRealName();
		}else{
			createName=name;
		}
		System.out.println("openId--"+openId);
		CbsServiceEntity service=new CbsServiceEntity();
		message = "申请设备移机成功";

		String eqNumber=request.getParameter("equipmentNum");
		String serviceDate=request.getParameter("serviceDate");
		String sn=request.getParameter("sn");
		CbsServiceTypeEntity sType1=systemService.singleResult("from CbsServiceTypeEntity where type=0 and name='增值服务'");
		CbsServiceTypeEntity sType2=systemService.singleResult("from CbsServiceTypeEntity where type=1 and name='移机'");
		try{
			service.setZyCinemaName(request.getParameter("cinemaName"));
			service.setTypename(request.getParameter("cinemaChain"));
			service.setContactsName(request.getParameter("contactsName"));
			service.setContactsPhone(request.getParameter("contactsPhone"));
			service.setEmail(request.getParameter("contactsEmail"));
			if(eqNumber!=null && !eqNumber.equals("")){
				service.setEquipmentNum(Integer.valueOf(eqNumber));
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			if(serviceDate!=null && !serviceDate.equals("")){
				service.setServiceDate(sdf.parse(serviceDate));
			}
			service.setDescription("设备台数:"+eqNumber+";希望服务时间:"+serviceDate);
			service.setServiceType1(sType1);
			service.setServiceType2(sType2);
			service.setSourceType("2");
			service.setStatus("1");
			service.setSn(request.getParameter("sn"));
			service.setSpeedStatus("0");

			ZyEquipmentSpareEntity zyEquipmentSpare=systemService.singleResult("from ZyEquipmentSpareEntity where sn='"+sn+"'");
			if(zyEquipmentSpare!=null){
				service.setZyEquipmentSpareId(zyEquipmentSpare);
			}
			ZyCinemaEntity cinema=systemService.singleResult("from ZyCinemaEntity where name='"+request.getParameter("cinemaName")+"'");
			if(cinema!=null){
				service.setZyCinemaId(cinema);
				service.setProvince(cinema.getProvince());
				if(cinema.getCity()!=null){
					TSTerritory city=systemService.get(TSTerritory.class,cinema.getCity());
					service.setCity(city);
				}
				service.setAddress(cinema.getAddress());
			}

			String hql="from ZyContactsEntity where cellphone1='"+request.getParameter("contactsPhone")+"' or cellphone2='"+request.getParameter("contactsPhone")+"'";
			List<ZyContactsEntity> zyContacts=systemService.findHql(hql);
			if(zyContacts.size()>0){
				service.setZyContactsId(zyContacts.get(0));
			}

			//组装服务单号CR+YYYYMMDD+001(增长)
//			String code ="";
//			Date date = new Date();
//			DateFormat format = new SimpleDateFormat("YYYYMMdd");
//			String time = format.format(date);
//			StringBuffer buffer = new StringBuffer();
//			buffer.append("CR");
//			buffer.append(time);
//			List<Object[]> cbsServiceList = systemService.findListbySql("select * from cbs_service where `code` not LIKE '%-%' AND to_days(create_date) = to_days(now()) ORDER BY create_date desc");
//
//			if (cbsServiceList.size() == 0) {
//				buffer.append("001");
//				code= buffer.toString();
//			} else {
//				String o = (String) cbsServiceList.get(0)[1];
//				String s = o.substring(10, 13);
//				int i = Integer.parseInt(s);
//				i++;
//				if (i <= 9) {
//					buffer.append("00" + i);
//				} else if (i >= 10 && i < 100) {
//					buffer.append("0" + i);
//				} else {
//					buffer.append("" + i);
//				}
//				code = buffer.toString();
//			}

			//新的服务单号
			Map noMap=cbsServiceServiceI.getNo();
			String code=(String) noMap.get("no");

			service.setCode(code);
			service.setCreateBy(createBy);
			service.setCreateName(createName);
			service.setCreateDate(new Date());
			systemService.save(service);

			//添加日志
			wxCommonService.addServiceLog(service.getId());

			/*给服务单客户联系人发送微信提醒*/
//			wxCommonService.sendWxMsg(service,user);
			//调用微信接口发送
			List<Map<String,String>> list=new ArrayList<>();
			String serviceCode="";
			if(service!=null){
				serviceCode=service.getCode();
			}
			String content="尊敬的客户：您的放映机<"+sn+">的服务申请已提交，服务单号：<"+serviceCode+">。我们会在30分钟内与您联系。【中影巴可客服部】";
			if(StringUtil.isNotEmpty(openId)){
				Map<String,String> map=new HashMap<>();
				map.put("openid",openId);
				map.put("message",content);
				list.add(map);
				wxCommonService.sendMsgForWx(list);
			}
			//发送邮件给HD
			wxCommonService.sendMail(service);

			//分别向400公共邮箱和400微信服务邮箱发送邮件
			//SendMailUtil.sendeMail("","","",systemService);

			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "添加失败";
			throw new BusinessException(e.getMessage());
		}
        j.setObj(service.getCode());
		j.setMsg(message);
		return j;
	}


}
